#!/bin/bash
# 生产环境一键部署脚本

set -e

echo "=========================================="
echo "开始生产环境部署..."
echo "=========================================="

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo "请使用root权限运行此脚本"
    exit 1
fi

# 项目路径
PROJECT_DIR="/opt/nanchang_tour"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"

# 1. 更新代码（如果使用Git）
if [ -d "$PROJECT_DIR/.git" ]; then
    echo "更新代码..."
    cd $PROJECT_DIR
    git pull
fi

# 2. 后端部署
echo ""
echo "部署后端..."
cd $BACKEND_DIR

# 激活虚拟环境
if [ ! -d "venv" ]; then
    echo "创建虚拟环境..."
    python3 -m venv venv
fi

source venv/bin/activate

# 安装/更新依赖
echo "安装Python依赖..."
pip install --upgrade pip
pip install -r requirements.txt
pip install gunicorn python-dotenv

# 检查.env文件
if [ ! -f ".env" ]; then
    echo "警告: .env文件不存在，请先创建并配置环境变量"
    echo "参考: docs/guides/完整部署指南.md"
fi

# 数据库迁移
echo "运行数据库迁移..."
python manage.py migrate --noinput

# 收集静态文件
echo "收集静态文件..."
python manage.py collectstatic --noinput

# 3. 前端部署
echo ""
echo "部署前端..."
cd $FRONTEND_DIR

# 安装依赖
if [ ! -d "node_modules" ]; then
    echo "安装Node.js依赖..."
    npm install
fi

# 构建生产版本
echo "构建前端..."
npm run build

# 复制到Nginx目录
echo "复制前端文件到Nginx目录..."
mkdir -p /var/www/nanchang-tour
cp -r dist/* /var/www/nanchang-tour/
chown -R www-data:www-data /var/www/nanchang-tour
chmod -R 755 /var/www/nanchang-tour

# 4. 创建日志目录
echo "创建日志目录..."
mkdir -p /var/log/nanchang-tour
chown -R www-data:www-data /var/log/nanchang-tour

# 5. 重启服务
echo ""
echo "重启服务..."

# 重新加载systemd
systemctl daemon-reload

# 重启Django服务
if systemctl is-active --quiet nanchang-tour; then
    echo "重启Django服务..."
    systemctl restart nanchang-tour
else
    echo "启动Django服务..."
    systemctl start nanchang-tour
    systemctl enable nanchang-tour
fi

# 重启Celery服务
if systemctl is-active --quiet celery-worker; then
    echo "重启Celery Worker..."
    systemctl restart celery-worker
else
    echo "启动Celery Worker..."
    systemctl start celery-worker
    systemctl enable celery-worker
fi

if systemctl is-active --quiet celery-beat; then
    echo "重启Celery Beat..."
    systemctl restart celery-beat
else
    echo "启动Celery Beat..."
    systemctl start celery-beat
    systemctl enable celery-beat
fi

# 重新加载Nginx
echo "重新加载Nginx..."
nginx -t && systemctl reload nginx

echo ""
echo "=========================================="
echo "部署完成！"
echo "=========================================="
echo ""
echo "服务状态:"
systemctl status nanchang-tour --no-pager -l
echo ""
echo "访问地址: http://your-server-ip"
echo ""

